package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.google.gson.Gson;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.SearchAdapter;
import com.luoxiang.socialandroid.adapter.Tuijian2RecyAdapter;
import com.luoxiang.socialandroid.adapter.TuijianRecyAdapter;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.SearchBean;
import com.luoxiang.socialandroid.bean.TypehostBean;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils2;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class SearchActivity extends BaseActivity {
    private TextView tx_quxiao;
    private String token;
    private EditText ed_search;
    private SearchAdapter searchAdapter;
    private RecyclerView rc_search, rc_search_tuijian;
    private Tuijian2RecyAdapter tuijianRecyAdapter;
    private RelativeLayout r_search;
    private int isfocus;
    private ImageView suijishengcheng;

    @Override
    protected void initListener() {
        tx_quxiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        ed_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String ed_text = ed_search.getText().toString();
                if (ed_text == null && ed_text.isEmpty()) {

                } else {
                    getSerch(EXTRA, token, ed_text, 1, 10);
                    r_search.setVisibility(View.INVISIBLE);
                    rc_search_tuijian.setVisibility(View.INVISIBLE);
                }
            }
        });
        ed_search.setOnKeyListener(onKey);
        suijishengcheng.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                getTypeHosts(token, EXTRA);
            }

            @Override
            protected void onFastClick() {

            }
        });
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_search);

    }

    View.OnKeyListener onKey = new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_ENTER) {
                InputMethodManager imm = (InputMethodManager) v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm.isActive()) {
                    imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), 0);
                }
                return true;
            }
            return false;
        }
    };


    @Override
    protected void initView() {
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        tx_quxiao = findViewById(R.id.tx_quxiao);
        ed_search = findViewById(R.id.ed_search);
        rc_search = findViewById(R.id.rc_search);
        r_search = findViewById(R.id.r_search);
        suijishengcheng = findViewById(R.id.suijishengcheng);
        rc_search_tuijian = findViewById(R.id.rc_search_tuijian);
        getRequest();
        getTypeHosts(token, EXTRA);
    }


    private void getSerch(String extra, String token, String keyword, int page, int limit) {
        NetUtils2.getInstance().getApiService().getSerch(extra, token, keyword, page, limit)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();
                        SearchBean searchbean = gson.fromJson(decryptStr, SearchBean.class);

                        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(SearchActivity.this);
                        rc_search.setLayoutManager(linearLayoutManager);
                        if (searchbean != null) {
                            if (searchbean.getData() != null) {
                                searchAdapter = new SearchAdapter(searchbean.getData().getUsers());
                                searchAdapter.setOnAddClickListener(new SearchAdapter.OnAddClickListener() {
                                    @Override
                                    public void onItemClicks(int position, int focus, int userid) {
                                        if (isfocus == 0) {
                                            isfocus = 1;
                                            focus(EXTRA, isfocus, userid);
                                        } else if (isfocus == 1) {
                                            isfocus = 0;
                                            focus(EXTRA, isfocus, userid);
                                        }
                                    }
                                });
                                searchAdapter.setOnAddClickListener2(new SearchAdapter.OnAddClickListener2() {
                                    @Override
                                    public void onItemClicks2(int userId) {
                                        Intent intent = new Intent(SearchActivity.this, DetailsActivity.class);
                                        intent.putExtra("userid", userId);
                                        startActivity(intent);
                                    }
                                });
                            }
                        }
                        rc_search.setAdapter(searchAdapter);
                    }


                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void focus(String extra, int isfocus, int userid) {
        NetUtils2.getInstance().getApiService().focus(token, extra, userid, isfocus)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStrf", decryptStr);
                        searchAdapter.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void getTypeHosts(String token, String extra) {
        NetUtils2.getInstance().getApiService().getTypeHosts2(token, extra, "6", 1, "6")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        showLoading();
                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        clearLoading();
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        LogUtils.i("decryptStr", decryptStr);
                        Gson gson = new Gson();

                        TypehostBean bean = gson.fromJson(decryptStr, TypehostBean.class);
                        GridLayoutManager gridLayoutManager = new GridLayoutManager(SearchActivity.this, 2, GridLayoutManager.VERTICAL, false);
                        rc_search_tuijian.setLayoutManager(gridLayoutManager);
                        if (bean != null) {
                            if (bean.getData() != null) {
                                tuijianRecyAdapter = new Tuijian2RecyAdapter(bean.getData().getHosts());
                                rc_search_tuijian.setAdapter(tuijianRecyAdapter);
                                tuijianRecyAdapter.setOnAddClickListener(new Tuijian2RecyAdapter.OnAddClickListener() {
                                    @Override
                                    public void onItemClicks(int position, int userid) {
                                        if (bean.getData().getHosts().get(position).getCoverType() == 0) {
                                            //跳转图片
                                            Intent intent = new Intent(SearchActivity.this, DetailsActivity.class);
                                            intent.putExtra("userid", userid);
                                            startActivity(intent);
                                        } else {
                                            //跳转视频
                                            Intent intent = new Intent(SearchActivity.this, VedioActivity.class);
                                            intent.putExtra("userid", userid);
                                            intent.putExtra("urls", "https://dahuixiong.oss-cn-shenzhen.aliyuncs.com/" + bean.getData().getHosts().get(position).getCover());
                                            startActivity(intent);
                                        }
                                    }
                                });
                            }
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                    }
                });
    }
}
